/**
 * 详情对话框
 */
var ActivityInfoDlg = {
    data: {
        type: "",
        content: "",
        goodsId: "",
        title: "",
        adminId: "",
        rewardWay: "",
        applyWay: "",
        maxAttendCount: "",
        maxApplicantsCount: "",
        alreadyApplicationsCount: "",
        alreadyApplicationsList: "",
        finalAttendCount: "",
        finalAttendList: "",
        submissList: "",
        rewardList: "",
        swParticipationWay: "",
        swRewardList: "",
        swReport: "",
        swTestList: "",
        praise: "",
        watch: "",
        status: "",
        beginApplyTime: "",
        endApplyTime: "",
        beginSubmissionTime: "",
        endSubmissionTime: "",
        activityEndTime: "",
        deptid: "",
        createTime: "",
        updateTime: "",
        recordStatus: ""
    },
    editor:null
};

layui.use(['form', 'admin', 'ax','laydate','tableSelect'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var tableSelect = layui.tableSelect;

    //让当前iframe弹层高度适应
    //admin.iframeAuto();

    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/activity/detail?id=" + Feng.getUrlParam("id"));
    var result = ajax.start();
    form.val('activityForm', result.data);
    //初始化图片
    var graphicList = result.data.graphicList;
    if(null!=graphicList && graphicList.length>0){
        for(var i=0;i<graphicList.length;i++){
            var img = graphicList[i].img;
            $("#pic_big").append('<img  src="'+Feng.ctxPath+img+'" width="100px" height="100px" layer-src="'+Feng.ctxPath+img+'" alt="'+i+'" >');
        }
    }else {
        $("#pic_big").append('<p style="text-align:  center"> 暂无图片</p>');
    }
    form.render();
    layer.photos({
        photos: '#pic_big'
        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });

    //初始化编辑器
    var E = window.wangEditor;
    var editor = new E('#description_toolbar', '#description_text');
    // 将图片大小限制为 2M
    editor.customConfig.uploadImgMaxSize = 200 * 1024 * 1024;
    editor.customConfig.uploadImgServer =Feng.ctxPath+'/upload/wang'; //'common/batch/imgUpdate';
    editor.customConfig.uploadFileName = 'file';
    editor.customConfig.customAlert = function (info){
        // info 是需要提示的内容
        alert('上传失败，请重试：' + info);
    }

    editor.create();
    ActivityInfoDlg.editor = editor;
    editor.txt.html(result.data.content);

    /**
     * 时间顺序校验
     * @param val
     * @returns {boolean}
     */
    ActivityInfoDlg.timeVerify=function(val){
        if(val.length<2){
            return true;
        }
        for(var i=0;i<val.length;i++){
            if(i+1>=val.length){
                return true;
            }
            if(val[i]==""||val[i+1]==""){
                return false;
            }
            var cha = (Date.parse(val[i]) - Date.parse(val[i+1])) / 86400000 * 24;
            if(cha<0){
                continue;
            }else {
                return false;
            }
        }
        return true;
    }
    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var b = ActivityInfoDlg.timeVerify([$("#beginSubmissionTime").val(),
            $("#endSubmissionTime").val(),$("#beginApplyTime").val(),$("#endApplyTime").val(),$("#activityEndTime").val()
        ]);
        if(!b){
            Feng.error("请正确填写活动时间，注意顺序");
            return false;
        }
        var ajax = new $ax(Feng.ctxPath + "/activity/editItem", function (data) {
            Feng.success("更新成功！");
            //传给上个页面，刷新table用
            admin.putTempData('formOk', true);

            //关掉对话框
            admin.closeThisDialog();
        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
        ajax.set("content",ActivityInfoDlg.editor.txt.html());
        ajax.set("swRewardList",$("#swRewardList").attr("checked")=="checked"?1:0);
        ajax.set("swReport",$("#swReport").attr("checked")=="checked"?1:0);
        ajax.set(data.field);
        ajax.start();
    });

    laydate.render({
        elem: '#beginApplyTime',
        type: 'datetime',
    });
    laydate.render({
        elem: '#endApplyTime',
        type: 'datetime',
    });
    laydate.render({
        elem: '#beginSubmissionTime',
        type: 'datetime',
    });
    laydate.render({
        elem: '#endSubmissionTime',
        type: 'datetime',
    });
    laydate.render({
        elem: '#activityEndTime',
        type: 'datetime',

    });
    ActivityInfoDlg.openApplyListDlg = function (id) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '投稿用户',
            area:["70%","70%"],
            maxmin:true,
            content: Feng.ctxPath + '/activity/apply?id=' + id,
            end: function () {
                admin.getTempData('formOk');
            }
        });
    };

    /**
     * 查看评论
     * @param id
     */
    ActivityInfoDlg.openCommentListDlg = function (id) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '评论',
            area:["70%","70%"],
            maxmin:true,
            content: Feng.ctxPath + '/comment?id=' + id+"&commentType=2",
            end: function () {
                admin.getTempData('formOk');
            }
        });
    };

    /**
     * 查看作品
     * @param id
     */
    ActivityInfoDlg.openWorkListDlg = function (id) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '用户作品',
            area:["70%","70%"],
            maxmin:true,
            content: Feng.ctxPath + '/works?activityId='+id+"&projectType=2",
            end: function () {
                admin.getTempData('formOk');
            }
        });
    };


    /**
     * 查看获奖名单
     * @param id
     */
    ActivityInfoDlg.openRewardListDlg = function (id) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '获奖名单',
            area:["70%","70%"],
            maxmin:true,
            content: Feng.ctxPath + '/activity/reward?id='+id,
            end: function () {
                admin.getTempData('formOk');
            }
        });
    };

    //投稿名单
    $('#finalBtnSearch').click(function () {
        ActivityInfoDlg.openApplyListDlg($("#activityId").val());
    });
    //评论表
    $('#commentBtn').click(function () {
        ActivityInfoDlg.openCommentListDlg($("#activityId").val());
    });
    //作品
    $('#workBtn').click(function () {
        ActivityInfoDlg.openWorkListDlg($("#activityId").val());
    });
    //获奖名单
    $('#rewardBtn').click(function () {
        ActivityInfoDlg.openRewardListDlg($("#activityId").val());
    });


    /**
     * 选择获奖人员
     */
    /*tableSelect.render({
        elem: '#selectRewardList',	//定义输入框input对象 必填
        checkedKey: 'playerId', //表格的唯一建值，非常重要，影响到选中状态 必填
        searchKey: 'userName',	//搜索输入框的name值 默认keyword-
        searchPlaceholder: '用户名',	//搜索输入框的提示文字 默认关键词搜索
        table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
            url:Feng.ctxPath+'/activity/canbeSelectList?id='+$("#activityId").val(),
            cols: [[
                {type: 'checkbox'},
                {field: 'playerId', title: 'id'},
                {field: 'userName', sort: true, align:'center',title: '用户名'},
                {field: 'headPic',hide:true, title: '头像'},
                {field: 'name', sort: true, align:'center',title: '收件人'},
                {field: 'address', sort: true, align:'center',title: '地址'},
                {field: 'phone', sort: true, align:'center',title: '电话'},
                {field: 'applyTime', sort: true, align:'center',title: '申请时间'},
            ]]
        },
        done: function (elem, data) {
            //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
            //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
            console.log(data.data.length)
            console.log(data.data[0].id)
            //alert(data[0][0].id)
            var a=[];
            for (var i=0;i<data.data.length;i++){
                var b={};
                b["playerId"]=data.data[i].playerId;
                b["activityId"]=$("#activityId").val();
                b["headPic"]=data.data[i].headPic;
                b["userName"]=data.data[i].userName;
                b["address"]=data.data[i].address;
                b["phone"]=data.data[i].phone;
                b["applyTime"]=data.data[i].applyTime;
                a.push(b)
            }
            var s = JSON.stringify(a);
            console.log(a)
            console.log(s)
            if(a.length<=0){
                return false;
            }else {
                var ajax = new $ax(Feng.ctxPath + "/activity/addSelectedList", function (data) {
                    Feng.success("选择成功");
                    //传给上个页面，刷新table用
                    admin.putTempData('formOk', true);
                    //关掉对话框
                    //admin.closeThisDialog();
                }, function (data) {
                    Feng.error("插入失败！" + data.responseJSON.message)
                });
                ajax.set("userList", s);
                ajax.start();
            }

        }
    })*/
    /**
     * 是否显示作品
     */
    form.on('switch(swReport)', function(data){
        console.log(data.elem); //得到checkbox原始DOM对象
        console.log(data.elem.checked); //开关是否开启，true或者false
        console.log(data.value); //开关value值，也可以通过data.elem.value得到
        console.log(data.othis); //得到美化后的DOM对象

    });
    /**
     * 是否显示中将名单
     */
    form.on('switch(swRewardList)', function(data){
        console.log(data.elem); //得到checkbox原始DOM对象
        console.log(data.elem.checked); //开关是否开启，true或者false
        console.log(data.value); //开关value值，也可以通过data.elem.value得到
        console.log(data.othis); //得到美化后的DOM对象

    });

});